﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data.Common;
using System.Collections;

namespace ShootSearch.Core.ObjectItems
{
    public class ObjectParser : IObjectParser
    {
        protected ObjectParserConfig config;

        #region IConfigable Members

        public SpiderManConfig Config
        {
            get { return config; }
            set
            {
                if (value is ObjectParserConfig)
                {
                    config = value as ObjectParserConfig;
                }
            }
        }

        #endregion

        public ObjectParser()
        {
            config = new ObjectParserConfig();
        }


        public bool Parse(object input, ref DbCommand cmd)
        {
            if (input is ObjectItem)
            {
                List<string> keys = new List<string>();
                List<string> keyparams = new List<string>();
                ObjectItem item = input as ObjectItem;
                for (int i = 0; i < item.Count; i++)
                {
                    string key = item.GetKey(i);
                    string value = item[i];

                    if (value != null)
                    {
                        keys.Add(string.Format(config.UniqueNameSpliter, key));
                        keyparams.Add("@" + key);
                        DbParameter dbparam = cmd.CreateParameter();
                        dbparam.ParameterName = "@" + key;
                        dbparam.Value = value;
                        cmd.Parameters.Add(dbparam);
                    }                 

                }

                if (keys.Count > 0)
                {
                    cmd.CommandText = string.Format(config.Insert,
                        string.Join(",", keys.ToArray()),
                        string.Join(",", keyparams.ToArray()));

                    return true;

                }
                else return false;


            }
            else return false;
        }

        
    }
}
